﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Data.Linq;

using Kunlun.Models;
using Kunlun.BusinessLogic;
using Kunlun.ViewModels;

namespace Kunlun.Controllers
{

    public class AccountController : Controller
    {

        #region 用户注册登录
        KunLunEntities entities = new KunLunEntities();
        KunlunMembership ship = new KunlunMembership();

        #region  客户登陆
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                Consumer user = KunlunConsumer.ValidateConsumer(model.UserName, model.Password);

                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    HttpCookie cookie = new HttpCookie("userId", user.ID.ToString());
                    Response.Cookies.Add(cookie);
                    if (model.RememberMe)
                    {
                        cookie.Expires = DateTime.Now.AddDays(30);
                    }
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "MyKunlun");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }
        #endregion

        #region 客户注册
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                if (ship.CheckEmail(model.Email) && ship.CheckName(model.UserName))
                {
                    string ip = Request.UserHostAddress;
                    int userid = ship.Register(model.UserName, model.Password, model.Email, ip);
                    HttpCookie cookie = new HttpCookie("userId", userid.ToString());
                    Response.Cookies.Add(cookie);
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    RegionSendMail.Send(model.Email, userid.ToString(), model.UserName, model.Password, "恭喜您成为引得好网站会员");

                    if (HttpContext.Request.Cookies != null && HttpContext.Request.Cookies["kunlun"] != null)
                    {
                        int rid = int.Parse(KunlunCookies.GetCookie("RecomandID"));
                        Recommend r = entities.Recommend.FirstOrDefault(u => u.ID == rid);
                        r.Register = userid;
                        int ruserid = int.Parse(KunlunCookies.GetCookie("Recomand"));
                        Consumer user = entities.Consumers.FirstOrDefault(u => u.ID == ruserid);
                        user.Scoring = user.Scoring + 3;
                        entities.SaveChanges();
                    }

                    return RedirectToAction("Index", "MyKunlun");
                }
                else
                {
                    ModelState.AddModelError("", "Email或用户名存在；");
                }


            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }
        #endregion

        #region 远程验证
        /// <summary>
        /// 远程验证注册客户邮箱
        /// </summary>
        /// <param name="Email">注册邮箱</param>
        /// <returns>是否有人注册</returns>
        [HttpGet]
        public ActionResult CheckEmail(string Email)
        {
            return Json(ship.CheckEmail(Email), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 远程验证注册客户名称
        /// </summary>
        /// <param name="UserName">客户名称</param>
        /// <returns>是否有人注册</returns>
        [HttpGet]
        public ActionResult CheckName(string UserName)
        {
            return Json(ship.CheckName(UserName), JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 退出"我的喀嚓"
        /// </summary>
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        #region 修改密码
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // 在某些出错情况下，ChangePassword 将引发异常，
                // 而不是返回 false。
                bool changePasswordSucceeded;
                try
                {
                    int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value.ToString());
                    Consumer currentUser = ship.GetUser(userid);
                    changePasswordSucceeded = ship.ChangePassword(currentUser, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }
        #endregion

        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
        [Authorize]
        public ActionResult ChangeEmail()
        {
            ViewBag.Message = "";
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangeEmail(ChangEmailModel model)
        {
            if (ModelState.IsValid)
            {
                int userid = Convert.ToInt32(Request.Cookies.Get("userId").Value.ToString());
                Consumer currentUser = ship.GetUser(userid);
                ship.ChangEmail(currentUser, model.Email);
            }
            ViewBag.Message = "修改成功";
            return View();
        }
        #endregion

        public ActionResult Confirm(string email, string id, string Url)
        {
            try
            {
                int userid = int.Parse(id);
                Consumer sumer = entities.Consumers.Single(s => s.ID == userid && s.Email == email);
                sumer.Status = 2;
                entities.Entry("sumer").State = System.Data.EntityState.Modified;
                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                WebLog.ErrorLog(ex);
            }
            return Redirect(Url);
        }
        public ActionResult GetPassword()
        {
            return View();
        }
    }
}
